import { lazy,useEffect } from 'react';
import {changeIsShowTarbar}from '../store/actions/tabbar'
import {changeLogin} from '../store/actions/login'
import { Route,Routes, useLocation, Navigate } from 'react-router-dom'
import { connect } from 'react-redux'; 
const Home = lazy(() => import('../pages/Home'));
const Login = lazy(() => import('../pages/Login'));
const Register = lazy(() => import('../pages/Register'));
const SongListDetails = lazy(() => import('../pages/SongListDetails'));
const PlaySong = lazy(() => import('../pages/PlaySong'));
const Comment = lazy(()=>import('../pages/Comment'))
const AllTopList = lazy(()=>import('../pages/AllTopList'))
const About = lazy(()=>import('../pages/About'))
const AppRouter = props => {
  const location = useLocation();
  const { pathname } = location;
  useEffect(()=>{
    routes.map(item=>{
        if(item.path===pathname){
          props.changeIsShowTarbar(item.tabbar)
        }
    })
  },[pathname])
  const routes = [
    {
      path: '/',
      auth: false,
      tabbar:true,
      component: <Navigate to='/home' />,
    },
    {
      path: '/home',
      auth: false,
      tabbar:true,
      component: <Home />,
    },
    {
      path:'/alltoplist',
      auth: false,
      tabbar:false,
      component:<AllTopList/>
    },
    {
        path:'/songlistdetails',
        auth: false,
        tabbar:false,
        component:<SongListDetails/>,
       
    },
    {
        path:'/playsong',
        auth: false,
        tabbar:false,
        component:<PlaySong/>,
    },
    {
      path:'/about',
      auth: true,
      tabbar:false,
      component:<About/>
    },
    {
      path:'/comment',
      auth: false,
      tabbar:false,
      component:<Comment/>,
    },
    {
      path: '/login',
      auth: false,
      tabbar:false,
      component: <Login /> 
    },
    {
      path: '/register',
      auth: false,
      tabbar:false,
      component: <Register /> 
    },
  ] 
  //请求页面路径需要验证 && 没有登录 -> 跳转登录页 ， 后续考虑登录后是否自动跳转被拦截路径 
  const RouteNav = (param) => {
    return (
      param.map((item) => {
        return (
          <Route path={item.path} element={item.path === pathname && item.auth && !props.login.isLogin ? <Navigate to='/login' replace={true}></Navigate> : item.component} key={item.path}>
            {
              item?.child && RouteNav(item.child)
            }
          </Route>
        )
      })
    )
  }
 
  return (
    <Routes>
      {
        RouteNav(routes)
      }
    </Routes>
  )
}
 

export default  connect(
    state =>({
      login:state.login
    }),{
      changeIsShowTarbar,
      changeLogin
    }
  )(AppRouter)